//
//  LEWebImage.m
//  CreditAddressBook
//
//  Created by Lee on 15/8/24.
//  Copyright (c) 2015年 Lee. All rights reserved.
//

#import "LEWebImage.h"
#import "CYHttpTool.h"
#import "SDImageCache.h"

@interface LEWebImage ()

@property (nonatomic, strong) SDImageCache *cache;
@end

@implementation LEWebImage

+ (LEWebImage *)sharedInstance {
    static LEWebImage *instance = nil;
    static dispatch_once_t token;
    
    dispatch_once(&token, ^{
        instance = [[self alloc] init];
    });
    
    return instance;
}

+ (void)downloadWithURL:(NSString *)url progress:(LEWebImageDownloaderProgressBlock)progressBlock completed:(LEWebImageCompletedWithFinishedBlock)completedBlock {
    
    [[LEWebImage sharedInstance] downloadWithURL:url progress:progressBlock completed:completedBlock];
}

- (void)downloadWithURL:(NSString *)url progress:(LEWebImageDownloaderProgressBlock)progressBlock completed:(LEWebImageCompletedWithFinishedBlock)completedBlock {

    SDImageCache *cache = [SDImageCache sharedImageCache];
    self.cache = cache;
    [cache queryDiskCacheForKey:url done:^(UIImage *image, SDImageCacheType cacheType) {
        if (image) {
            completedBlock(image, nil, YES);
        } else {
            [CYHttpTool getSerializerWithURL:url params:nil success:^(id json) {
                UIImage *image = [UIImage imageWithData:json];
                if (image) {
                    //缓存图片
                    [cache storeImage:image forKey:url];
                    if (completedBlock) {
                        completedBlock(image, nil, YES);
                    }
                }
            } failure:^(NSError *error) {
                if (completedBlock) {
                    completedBlock(nil, error, NO);
                }
            }];
        }
    }];
}

+ (void)clearMemory {
    LEWebImage *webImage = [LEWebImage sharedInstance];
    [webImage.cache clearMemory];
}
@end
